package com.mtzqc.common.kt

import android.content.Context
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.StringUtils
import com.didi.drouter.api.DRouter
import com.didi.drouter.router.Request
import com.didi.drouter.router.RouterCallback
import com.mtzqc.common.service.IService


inline fun <reified T : IService> loadService(alias: String? = null): T {
    return getService(alias)!!
}

inline fun <reified T : IService> getService(alias: String? = null): T? {
    return DRouter.build(T::class.java).also {
        if (!StringUtils.isEmpty(alias)) {
            it.setAlias(alias)
        }
    }.getService()
}


inline fun createRequest(path: String?, block: Request.() -> Unit): Request {
    return DRouter.build(path)
        .also(block)
}

inline fun String?.startActivity(
    ctx: Context? = null,
    block: Request.() -> Unit = {},
) {
    startActivityForResult(ctx, block)
}

inline fun String?.startActivityForResult(
    ctx: Context? = null,
    block: Request.() -> Unit = {},
    result: RouterCallback? = null
) {
    createRequest(this, block).start(ctx, result)
}


inline fun <reified F : Fragment> String?.fragment(
    block: (Request) -> Unit = {}
): F {
    var fragment: F? = null
    startActivityForResult(null, block) {
        fragment = it.fragment as F?
    }
    return fragment!!
}